package kr.hkit.powerjava.chapter24.work2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class StudentDao implements InterfaceDao<Student> {
	private ArrayList<Student> list;
	private static final String FILE_NAME = "StudentList";
	
	@Override
	public void insertItem(Student Item) {
		if (!list.contains(Item)) {
			list.add(Item);
		} else {
			System.out.println("중복된 데이터");
		}
	}

	@Override
	public void deleteItem(Student Item) {
		if (!list.contains(Item)) {
			list.remove(Item);
		} else {
			System.out.println("학생정보 없음");
		}
	}

	@Override
	public void updateItem(Student Item) {
		Student temp = new Student(Item.getStdNum(), Item.getStdName());
		if (list.contains(temp)) {
			list.set(list.indexOf(Item), Item);
		} else {
			System.out.println("일치하는 학생 없음");
		}
	}

	@Override
	public void searchItem(Student ITem) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void prnItem(Comparator<Student> comp) {
		if (comp == null){
			Collections.sort(list);
		} else {
			Collections.sort(list, comp);
		}
		for (Student std : list)
			System.out.println(std);
	}

	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(FILE_NAME)));
			list = (ArrayList<Student>)ois.readObject();
		} catch (FileNotFoundException e) {
			try {
				new File(FILE_NAME).createNewFile();
				list = new ArrayList<>();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) try { ois.close(); } catch (IOException e) {}
		}
		
	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
			oos.writeObject(list);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null) try { oos.close(); } catch (Exception e) {}
		}
	
	}



}
